package com.fly.feishu.web.lisener.register;

import com.fly.feishu.web.lisener.FeishuTopicListener;
import com.fly.feishu.web.lisener.annotation.FeishuTopic;
import com.google.common.collect.Maps;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.*;

@Component
public class FeishuTopicRegister implements ApplicationContextAware {

    private static Map<FeishuTopicListener, String[]> feishuTopicMap = Maps.newHashMap();

    private static ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
        setFeishuTopicMap();
    }

    private static void setFeishuTopicMap() {
        Map<String, FeishuTopicListener> beans = applicationContext.getBeansOfType(FeishuTopicListener.class);
        if (CollectionUtils.isEmpty(beans)) {
            return;
        }
        Collection<FeishuTopicListener> values = beans.values();
        values.stream().forEach(obj -> {
            FeishuTopic annotation = obj.getClass().getAnnotation(FeishuTopic.class);
            if (annotation == null) {
                return;
            }
            String[] topics = annotation.topic();
            feishuTopicMap.put(obj, topics);
        });
    }

    public static FeishuTopicListener getListener(String topic) {
        if (CollectionUtils.isEmpty(feishuTopicMap)) {
            setFeishuTopicMap();
        }

        Set<Map.Entry<FeishuTopicListener, String[]>> entries = feishuTopicMap.entrySet();
        Iterator<Map.Entry<FeishuTopicListener, String[]>> iterator = entries.iterator();
        while (iterator.hasNext()) {
            Map.Entry<FeishuTopicListener, String[]> next = iterator.next();
            String[] values = next.getValue();
            if (Arrays.asList(values).contains(topic)) {
                return next.getKey();
            }
        }
        return null;
    }
}
